package cn.edu.thu.laud.thrift;
import java.util.Arrays;
import java.util.List;

import org.apache.cassandra.service.AbstractCassandraDaemon;
import org.apache.cassandra.thrift.CassandraDaemon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LaUDDaemon  extends CassandraDaemon{
	public static LaUDDaemon instance;
	static
	{
		AbstractCassandraDaemon.initLog4j();
	}
	static Logger logger = LoggerFactory.getLogger(CassandraDaemon.class);
	final static String SYNC = "sync";
	final static String ASYNC = "async";
	final static String HSHA = "hsha";
	public final static List<String> rpc_server_types = Arrays.asList(SYNC, ASYNC, HSHA);
	private LaUDServer server;//thrift server
	private LaUDDataServer dataServer;
	private String[] args;
	public LaUDCassandraServer getCassandraServer(){
		return this.server.getLaUDCassandraServer();
	}
	protected void startServer()
	{
		//try {
		//listenAddr= InetAddress.getByName(LaUDLogUtils.parser.getElementString("ServerIP",listenAddr.getHostAddress()));
		//listenPort=Integer.parseInt(LaUDLogUtils.parser.getElementString("ServerPort",listenPort));
		//			} catch (UnknownHostException e1) {
		//				e1.printStackTrace();
		//			}
		if (server == null)
		{
			server = new LaUDServer(listenAddr, listenPort,args);
			server.start();
		}
		if(dataServer==null){
			try {
				dataServer=new LaUDDataServer(listenAddr,Integer.parseInt(LaUDLogUtils.parser.getElementString("DataServerPort",listenPort+1)));
				dataServer.start();
			} catch (Exception e) {
				e.printStackTrace();
				stopServer();
				deactivate();
			}

		}
	}

	protected void stopServer()
	{
		logger.warn("laudDaemon will be closed..................");
		if (server != null)
		{
			server.stopServer();
			try
			{
				server.join();
			}
			catch (InterruptedException e)
			{
				logger.error("Interrupted while waiting thrift server to stop", e);
			}
			server = null;
		}
		if(dataServer!=null){
			dataServer.stopServer();
			dataServer=null;
		}
	}

	public static void stop(String[] args)
	{
		instance.stopServer();
		instance.deactivate();
	}

	public static void main(String[] args)
	{
		
		instance = new LaUDDaemon();
		instance.args=args;
		instance.activate();
	}

}
